import collections


class Solution(object):
    def validSubarrays(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        stack = collections.deque()
        n = len(nums)
        total = 0
        for i in range(n):
            if not stack:
                stack.append(i)
            else:
                if nums[i] >= nums[stack[-1]]:
                    stack.append(i)
                else:
                    while stack and nums[stack[-1]] > nums[i]:
                        stack.pop()
                    stack.append(i)
            total += len(stack)
        return total


data = Solution()
nums = [1, 4, 2, 5, 3]
print(data.validSubarrays(nums))
nums = [3, 2, 1]
print(data.validSubarrays(nums))
nums = [2]
print(data.validSubarrays(nums))
